const express = require('express')
const router = express.Router()
//引入创建Id方法
const { createId, createToken } = require('../util/index')
//引入mysql
const mysql = require('mysql');
//状态
const { status200, status500 } = require('../status/index')
//剔除
const { filterObject, createIds } = require('../util/tool')

const svgCaptcha = require('svg-captcha')
const nodeCache = require('node-cache');
const jwt = require('jsonwebtoken')
const myCache = new nodeCache({ stdTTL: 60, checkperiod: 7200 });
const { env } = require('../dataBase')
//线上数据库
// const env = {
//     host: "111.231.22.97",
//     user: "cqbase",
//     password: "MZM5j38RNCjdPRP7",
//     database: "cqbase", //数据库名字
//     multipleStatements: true //允许多条sql语句查询
// };


/* 
@注册
*/
//判断有无用户名
const usernameDeter = (username, pool) => {
    return new Promise((resolve, reject) => {
        let sql = 'select * from userlist where username = ?'
        pool.query(sql, [username], (err, result) => {
            try {
                if (result.length == 0) {
                    resolve(true)
                }
                else {
                    resolve(false)
                }
            } catch {
                console.log(err, 'err')
                res.status(500)
            }
        })
    })
}
//添加
const successPost = (req, res, pool) => {
    let { username, password, name, phone, like, age, email } = req.body
    let sql = 'insert into userlist values (?,?,?,?,?,?,?,?,?)'
    let arrs = [createId(), username, password, name, phone, like, age, '0', email]
    pool.query(sql, arrs, (err, result) => {
        try {
            if (result.affectedRows >= 1) {
                status200(res, {})
            }
            else {
                status500(res, { msg: '注册失败,请重新注册' })
            }
        } catch {
            console.log(err, 'error')
            res.status(500)
        }
    })
}
const postRegister = async (req, res) => {
    let pool = mysql.createPool(env)
    const usernameDe = await usernameDeter(req.body['username'], pool)
    if (!usernameDe) {
        //调用返回接口函数
        status500(res, { msg: "用户名已注册" })
        return
    }
    //成功注册
    successPost(req, res, pool)
}
router.post('/register', (req, res) => {
    postRegister(req, res)
})



/* 
@ 登录
*/

const postLogin = (req, res) => {
    let pool = mysql.createPool(env)
    pool.query('select *  from userlist where username = ? and password = ?', [req.body['username'], req.body['password']], (err, result) => {
        try {
            if (result.length == 1) {
                status200(res, { data: { token: createToken(req) } })
            }
            else {
                status500(res, { msg: '登录失败,请重新登录' })
            }

        } catch {
            console.log(err)
            res.status(500)
        }
    })
}
router.post('/login', (req, res) => {
    /* 验证,不通过就提示验证码未过 */
    let code = myCache.get(req.body['username'])
    console.log(code)
    if (code != req.body.code) {
        res.send({
            code: 500,
            msg: '验证码失败'
        })
        return
    }
    /* 验证,通过进行下一步 */
    postLogin(req, res)
})

/* 
@验证码
 */
router.get('/getCode', (req, res) => {
    const ids = req.query['username']
    //进阶配置
    const captchaOption = {
        size: 4, // 字符数
        ignoreChars: "0oil", // 过滤字符
        noise: 2, // 干扰线条数
        color: true,
        background: "#fff", // 背景颜色
    }
    const captcha = svgCaptcha.create(captchaOption)
    myCache.set(ids, captcha.text.toLowerCase(), 60)
    res.type('svg')
    res.status(200).send(captcha.data)
})


/* 
@获取个人信息
*/
const personInfo = (req, res) => {
    const secretKey = 'chouqin'
    jwt.verify(req.headers['authorization'], secretKey, (err, decode) => {
        if (err) {
            res.status(500)
            console.log(err, 'error')
        }
        else {
            console.log(decode, 'decode')
            const username = decode['username']
            let sql = 'select * from userlist where username=?'
            let pool = mysql.createPool(env)
            pool.query(sql, [username], (err, result) => {
                try {
                    //返回id、username、name、phone、role等字段
                    status200(res, { data: filterObject(result[0], ["password"]) })
                } catch {
                    res.status(500)
                    console.log(err, 'error')
                }

            })
        }
    })

}

router.get('/personInfo', (req, res) => {
    personInfo(req, res)
})


/*
修改密码
 */
router.post('/updatePassword', (req, res) => {
    let { id, password } = req.body
    console.log(id, password)
    let pool = mysql.createPool(env)
    pool.query('update userlist set password = ? where id = ?', [password, id], (err, result) => {
        try {
            if (result.affectedRows >= 1) {
                status200(res, { msg: 'success' })
            }
            else {
                status500(res, { msg: 'error' })
            }
        } catch {
            res.status(500)
            console.log(err, 'error')
        }
    })
})



/* 
@忘记密码
@用邮箱更新
*/
const nodemailer = require('nodemailer')
const transporter = nodemailer.createTransport({
    host: "smtp.163.com",     // SMTP服务器地址  qq是smtp.qq.com
    port: 465,                    // SMTP端口
    secure: true,                 // 使用SSL/TLS
    auth: {
        user: "17336331895@163.com",  // 邮箱账号
        pass: "HURf7JEQDxTC7pdC"            // 授权码
    }
});
router.post('/postMail', async (req, res) => {
    let str = createIds([0, 0, 0, 0])
    let content = `<b><div>wangs say to you code ${str}</div></b>`
    let { username, email } = req.body
    //允许5分钟内修改
    myCache.set(`${username}123`, str, 300)
    const mailOptions = {
        from: '17336331895@163.com', // 发件人
        subject: '验证码',
        to: `${email}`,             // 收件人
        html: content                 // HTML内容
    }
    const info = await transporter.sendMail(mailOptions);
    if (info.messageId) {
        status200(res, { msg: 'success' })
    }
    else {
        status500(res, { msg: 'error' })
    }
})
router.post('/updateForgetPassword', (req, res) => {
    let { password, code, username } = req.body
    let codes = myCache.get(`${username}123`)
    //判断正确往下走
    if (code == codes) {
        let pool = mysql.createPool(env)
        pool.query('update userlist set password = ? where username = ?', [password, username], (err, result) => {
            try {
              if(result.affectedRows>=1){
                status200(res,{msg:'修改成功'})
                return
              }
              status500(res,{msg:'修改失败'})
            } catch {
              res.status(500)
              console.log(err,'error')
            }
        })
    }
    else {
        status500(res, { msg: '验证码错误' })
    }
})


module.exports = router